package org.cloudie.docs.editor.client.storage.items;

import java.util.ArrayList;
import java.util.Date;

public class VirtualSystem {
  
  private static int maxId = 0;
  private static String prefixId = "i" + (new Date()).getTime() + "-";
  private static ArrayList<VirtualSystemEntry> entries =
      new ArrayList<VirtualSystemEntry>();
  private VirtualSystem() { }
  
  public static boolean hasChildren(String id) {
	for (VirtualSystemEntry entry : entries) {
	  String parent = entry.getParent();
	  if (parent != null && parent.equals(id)) {
		return true;
	  }
	}
	return false;
  }
  
  public static VirtualSystemEntry removeEntry(String id) {
    VirtualSystemEntry entry = getEntry(id);
    if (entry != null) {
      entries.remove(entry);
      return entry;
    }
    return null;
  }
  
  public static void removeChildEntries(String folderId) {
	VirtualSystemEntry[] toRemove = getEntries(folderId);
	for (VirtualSystemEntry entry : toRemove) {
	  entries.remove(entry);
	}
  }
  
  public static void addEntry(VirtualSystemEntry entry) {
    entries.add(entry);
  }
  
  public static String getNextId() {
    return prefixId + ++maxId;
  }
  
  public static VirtualSystemEntry getEntry(String id) {
    for (VirtualSystemEntry entry : entries) {
      if (entry.getId().equals(id)) {
	    return entry;
      }
	}
    return null;
  }
  
  public static ArrayList<VirtualSystemEntry> getEntries() {
    return entries;
  }
  
  public static void setEntries(ArrayList<VirtualSystemEntry> allEntries) {
    for (VirtualSystemEntry entry : allEntries) {
      addEntry(entry);
    }
  }
  
  public static VirtualSystemEntry[] getEntries(String folderId) {
	ArrayList<VirtualSystemEntry> contents = new ArrayList<VirtualSystemEntry>();
	for (int i=0; i<entries.size(); i++) {
      VirtualSystemEntry entry = entries.get(i);
      if ((entry.getParent() == null && folderId == null) ||
          (entry.getParent() != null && entry.getParent().equals(folderId))) {
        contents.add(entry);
      }
    }
    return contents.toArray(new VirtualSystemEntry[contents.size()]);
  }
  
  public static VirtualSystemEntry setEntryLabel(String id, String newLabel) {
    VirtualSystemEntry entry = getEntry(id);
    if (entry != null) {
      entry.setLabel(newLabel);
      return entry;
    }
    return null;
  }
  
  public static VirtualSystemEntry setEntryParent(String id, String newParentId) {
    VirtualSystemEntry entry = getEntry(id);
	if (entry != null) {
	  entry.setParent(newParentId);
	  return entry;
	}
	return null;
  }
  
}
